<?php


namespace App\Api\Controllers\YSEPay;


class Applyment
{
    private $domain = 'http://center.5ft.wiki';

    private function _exception($msg, $code)
    {
        throw new \Exception($msg, $code);
    }

    private function curlPost($url, $params, $data, $timeout = 20)
    {
        if (is_array($params)) {
            $url .= '?' . http_build_query($params);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        if ($data != '') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        // 禁用证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $curlResponse = curl_exec($ch);
        $curlCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlMsg = curl_error($ch);
        curl_close($ch);
        if (!$curlResponse) {
            $this->_exception('curl请求失败：' . $curlMsg);
        }
        return $curlResponse;
    }

    public function apply($company = '', $store_id = '')
    {
        $url = implode('/', [$this->domain, 'api/channel_applyment/applyment']);
        $json = $this->curlPost($url, [
            'user_id' => 0,
            'company' => $company,
            'store_id' => $store_id,
        ], [
            'key' => 'bDosMM2gqX'
        ]);
        $result = json_decode($json, true);
        if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
            throw new \Exception('数据解析异常，请联系管理员');
        }
        if ($result['code'] != 1) {
            throw new \Exception($result['msg']);
        }
        return $result;
    }
}